package com.lgy.springboot_example.aspect;

import com.lgy.springboot_example.async.AsyncManager;
import com.lgy.springboot_example.dto.OrderDelay;
import com.lgy.springboot_example.entity.OrderInfo;
import com.lgy.springboot_example.mapper.OrderInfoMapper;
import com.lgy.springboot_example.utils.DataResult;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.DelayQueue;

@Aspect
@Component
public class OrderInfoAspect {

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private AsyncManager sync;

    private DelayQueue<OrderDelay> delayDelayQueue;

    @PostConstruct
    public void init() {
        System.out.println("项目初始化启动！！！");
        this.delayDelayQueue = new DelayQueue<>();
        List<OrderInfo> list = orderInfoMapper.getNotPayOrderInfo();
        for (OrderInfo orderInfo : list) {
            OrderDelay orderDelay = new OrderDelay();
            orderDelay.setId(orderInfo.getOrderId());
            orderDelay.setExpireTime(orderInfo.getCreateTime().getTime());
            delayDelayQueue.put(orderDelay);
        }
        new Thread(() -> {
            try {
                while (true) {
                    OrderDelay take = delayDelayQueue.take();
                    System.out.println("走你！！！！！");
                    orderInfoMapper.updateOrderStatusByOrderId(take.getId(), -1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start(); // 此处记得使用start()方法启动线程
    }

    @Pointcut("execution(* com.lgy.springboot_example.controller.OrderInfoController.*(..))")
    private void todo() {
    }

    @AfterReturning(value = "todo()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, DataResult result) {

        if (result.getStatus() != 1) return;

        String methodName = joinPoint.getSignature().getName();//方法名

        if (methodName.equals("insertOrder")) {
            sync.todo(() -> {
                //获取所有的参数列表
                //Object[] args = joinPoint.getArgs();
                //OrderInfo oi = (OrderInfo) args[0];
                Integer id = (int) result.getData();
                OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(id);
                OrderDelay orderDelay = new OrderDelay();
                orderDelay.setId(id);
                orderDelay.setExpireTime(orderInfo.getCreateTime().getTime());
                delayDelayQueue.put(orderDelay);
            });
        }
    }
}
